package com.expensecontrol.action;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.LinkedHashMap;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.struts2.interceptor.ServletRequestAware;
import org.apache.struts2.interceptor.ServletResponseAware;
import org.json.JSONException;
import org.json.JSONObject;

import com.opensymphony.xwork2.Action;

public class JSONDataAction implements ServletRequestAware, ServletResponseAware{
	//
	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	private HttpServletRequest servletRequest;
	private HttpServletResponse servletResponse;
	
	private String status;
	private String xpin;

	public String execute(){
		System.out.println("Inside");
		//System.out.println("Inside"+getServletRequest().getReader());
		JSONObject respObj = new JSONObject();
		PrintWriter out=null;
		try {
			BufferedReader bufferedReader = getServletRequest().getReader();
			String line = null;  
			StringBuffer sb=new StringBuffer();
			while ((line = bufferedReader.readLine()) != null) {  
			    sb.append(line + "\n");  
			}
			bufferedReader.close();
			System.out.println("Test : "+sb.toString());
			JSONObject jsonObject=new JSONObject(sb.toString());
			/*this.xpin=jsonObject.getString("xpin");
			System.out.println(this.xpin);
			if(xpin.equals("123")){
				status="Paid";
			}else if(xpin.equals("124")){
				status="Pending";
			}else{
				status="Invalid Xpin"; 
			}
			System.out.println("response1");
			out = getServletResponse().getWriter();
			System.out.println("response3");*/
			out = getServletResponse().getWriter();
			
			status="success "+jsonObject.getString("expenseDate")+" "+jsonObject.getString("expenseAmt")+" "+jsonObject.getString("expenseType");
			respObj.put("status", status);      
			System.out.println("response4");
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (JSONException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}		
		System.out.println("response5");
		System.out.println(respObj.toString());
		out.print(respObj);
		out.flush();
		System.out.println("completted");
		return Action.SUCCESS;
	}
	public HttpServletRequest getServletRequest() {
		return servletRequest;
	}
	public void setServletRequest(HttpServletRequest servletRequest) {
		this.servletRequest = servletRequest;
	}
	public HttpServletResponse getServletResponse() {
		return servletResponse;
	}
	public void setServletResponse(HttpServletResponse servletResponse) {
		this.servletResponse = servletResponse;
	}
	
}